package captcha

import (
	"errors"
	"time"
	"wskyygyso/api/pkg/app"
	"wskyygyso/api/pkg/config"
	"wskyygyso/api/pkg/redis"
)

//RedisStore 实现 base64Captcha.Store 接口
type RedisStore struct {
	RedisClient *redis.RedisClient
	KeyPrefix   string
}

//Set 设置验证码
func (s *RedisStore) Set(id string, value string) error {
	ExpireTime := time.Minute * time.Duration(config.GetInt64("captcha.expire_time"))
	if app.IsLocal() {
		ExpireTime = time.Minute * time.Duration(config.GetInt64("captcha.debug_expire_time"))
	}
	if ok := s.RedisClient.Set(s.KeyPrefix+id, value, ExpireTime); !ok {
		return errors.New("无法存储验证码数据")
	}
	return nil
}

//Get 获取验证码
func (s *RedisStore) Get(id string, clear bool) string {
	key := s.KeyPrefix + id
	val := s.RedisClient.Get(key)
	if clear {
		s.RedisClient.Del(key)
	}
	return val

}

//Verify 验证码 验证
func (s *RedisStore) Verify(id, answer string, clear bool) bool {
	key := s.KeyPrefix + id
	val := s.RedisClient.Get(key)
	if val == answer {
		if clear {
			s.RedisClient.Del(key)
		}
		return true
	}
	return false
}
